package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author bueryouth
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    UserMapper userMapper;

    /**
     * 新增接口
     */
    @PostMapping
    public Result<?> save(@RequestBody UserEntity userEntity) {
        // 设置默认密码
        if (userEntity.getPassword() == null) {
            userEntity.setPassword("123456");
        }
        if (userEntity.getRole() == null) {
            userEntity.setRole("0");
        }
        userMapper.insert(userEntity);
        return Result.success();
    }

    /**
     * 更新接口
     */
    @PutMapping
    public Result<?> update(@RequestBody UserEntity userEntity) {
        userMapper.updateById(userEntity);
        return Result.success();
    }

    /**
     * 删除接口
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 查询id接口
     */
    @GetMapping("/{id}")
    public Result<?> selectId(@PathVariable Long id) {
        return Result.success(userMapper.selectById(id));
    }

    /**
     * 查询接口
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum, // 设置接口默认查询内容
        @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<UserEntity> wrapper = Wrappers.lambdaQuery();
        // 查询字段为空情况
        if (StrUtil.isNotEmpty(search)) {
            wrapper.like(UserEntity::getNickName, search);
        }
        Page<UserEntity> userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(userPage);
    }
}
